// base
import Taro, { Component } from '@tarojs/taro'
import { View, Image, Form, Button, ScrollView } from '@tarojs/components'
// redux
import { connect } from '@tarojs/redux'
import {
  DOREQUESTJOBVIEW,
  DOREQUESTPEOPLE,
  getJobCateList,
  DOREQUESTBANNER
} from './store/actions/pagejobview'
import { DOREQUESTCHANGECP } from '../self-center/store/actions/pageselfcenter'
import { UPDATEPAGEJOBVIEW } from './store/types/pagejobview'
import { UPDATEIM } from '../../store/types/im'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import { UPDATELANDMARK } from '../../store/types/landmark'
// less
import './index.less'
import {
  getZhichuBUserInfo,
  getZhichuUserInfo,
  updateCompanyId
} from '../../store/actions/userinfo'
import { getLocation } from '../../crossplatform/apiservice/location'
import { positioning } from '../../store/actions/landmark'
import { stopPullDownRefresh } from '../../crossplatform/apiservice/reflash'
import BarLevelone from './components/bar-levelone'
import TopLocation from './components/top-location'
import JobsScrollWrap from './components/jobs-scroll-wrap'
import ResumeScrollWrap from './components/resume-scroll-wrap'
import { deepCopy } from '../../util/lodashmin'
import { pageScrollTo } from '../../crossplatform/apiservice/pageScrollTo'
import StickyWrap from '../../components/taro-ui/sticky-wrap'
import { showToast } from '../../crossplatform/apiservice/toast'
import { getStorageSync } from '../../crossplatform/apiservice/storage'
import messagePush from '../../util/messagePush'
import ScreenList from '../../components/page-components/screen-list'
import { getAreaListByCityName } from '../../service/user-controller'
import { inRecruitPostCategoryRequest } from '../../service/user-archive-controller'
import { getGlobalData } from '../../configuration/globaldata'
import wxLogin from '../../util/wxLogin'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGEJOBVIEW,
      payload: {
        ...payload
      }
    })
  },
  dorequest(payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTJOBVIEW(payload)
      dispatch(promise)
      promise.payload.then(() => {
        resolve()
      })
    })
  },
  updateLandmark(payload) {
    dispatch({
      type: UPDATELANDMARK,
      payload: {
        ...payload
      }
    })
  },
  getCity(payload) {
    return new Promise(resolve => {
      let promise = positioning(payload)
      dispatch(promise)
      promise.payload.then(() => {
        resolve()
      })
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  doRequestForPeople(payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTPEOPLE(payload)
      dispatch(promise)
      promise.payload.then(() => {
        resolve()
      })
    })
  },
  doRequestGetBanner(payload) {
    return new Promise(resolve => {
      let promise = DOREQUESTBANNER(payload)
      dispatch(promise)
      promise.payload.then(() => {
        resolve()
      })
    })
  },
  getZhichuUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  getZhichuBUserInfo(payload) {
    return new Promise(resolve => {
      let promise = getZhichuBUserInfo(payload)
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  },
  queryCate(type) {
    let promise = getJobCateList(type)
    dispatch(promise)
    return promise.payload
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  queryCompanyInfo(payload) {
    return dispatch(DOREQUESTCHANGECP(payload))
  },
  updateCompany() {
    dispatch(updateCompanyId())
  }
})

@connect(
  ({ pagejobview, landmark, userinfo, im }) => ({
    ...pagejobview,
    ...userinfo,
    ...im,
    landmarkName: landmark.landmarkName
  }),
  mapActiontoProps
)
class JobView extends Component {
  static defaultProps = {
    peopleDataSource: [],
    dataSource: [[], [], [], []]
  }

  constructor(props) {
    super(props)
    this.state = {
      barlevelonedata: [{ title: '兼职' }, { title: '实习' }, { title: '全职' }],
      prevRole: 'personal',
      isiPhone: false,
      screenTitle: [
        {
          name: '排序',
          type: 'list',
          title: false,
          data: []
        },
        {
          name: '职位',
          type: 'card',
          title: true,
          data: []
        },
        {
          name: '区域',
          type: 'card',
          title: false,
          data: []
        },
        {
          name: '学历',
          type: 'card',
          title: true,
          data: []
        }
      ],
      screenShow: false,
      screenIndex: -1,
      loadIn: true
    }
  }

  config = {
    enablePullDownRefresh: true,
    disableSwipeBack: true,
    onReachBottomDistance: 100
  }
  requestOver = true

  componentWillMount() {
    // onLoad
    wxLogin.props = this.props
    const { landmarkName } = this.props
    this.setState({
      loadIn: true
    })
    wxLogin.doLogin().then(() => {
      this.lastLandmarkName = landmarkName
      this.props.doRequestGetBanner()
      landmarkName && this.queryWrap()
      // 判断是否是iphone
      this.setState({
        isiPhone: getStorageSync('iPhone')
      })
      this.setLocation().then(() => {
        this.getScreenData()
      })
    })
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    const { loadIn, prevRole } = this.state
    const { role, landmarkName } = this.props
    this.props.updateState({
      requestOverTop: true
    })
    if (prevRole != role && landmarkName && !loadIn) {
      this.queryWrap()
    }
    // this.islandmarkNameChange()
    this.getVipStatus()

    !loadIn && this.getScreenData()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.landmarkName && this.lastLandmarkName != nextProps.landmarkName) {
      this.lastLandmarkName = nextProps.landmarkName
      this.queryWrap()
    }
  }

  componentDidHide() {
    // onhide
    this.onHideScreen()
    this.setState({
      loadIn: false
    })
  }

  componentWillUnmount() {
    // onUnload
    this.onHideScreen()
    this.setState({
      loadIn: false
    })
  }

  lastLandmarkName = null

  // islandmarkNameChange = () => {
  //   if (this.lastLandmarkName != this.props.landmarkName) {
  //     this.lastLandmarkName = this.props.landmarkName
  //     this.queryWrap()
  //   }
  // }
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    const url = '/pages/job-view/index'

    return {
      title: '我推荐一个无中介，大学生永久免费的兼职平台。',
      path: url,
      imageUrl: 'https://imagesize.hrwork.com/sp/files/111fafd2-f97a-4f6c-aefd-ad468ca64278.png'
    }
  }

  getVipStatus = () => {
    const { companyId = '', role } = this.props
    role == 'company' &&
      this.props.queryCompanyInfo({ companyId }).then(({ payload: { status, entry, message } }) => {
        if (status) {
          this.props.updateUserState({
            isVip: !!entry
          })
        } else {
          showToast({
            title: message || 'queryCompanyInfo失败'
          })
        }
      })
  }

  setLocation = () => {
    return new Promise(resolve => {
      if (!this.props.landmarkName) {
        getLocation()
          .then(res => {
            const { latitude, longitude } = res
            this.props.updateUserState({
              latitude,
              longitude
            })
            this.props.getCity({ lat: latitude, lng: longitude }).then(() => {
              resolve()
            })
          })
          .catch(() => {
            this.props.updateLandmark({
              landmarkName: '上海',
              cityId: 15
            })
            this.props.updateUserState({
              latitude: '',
              longitude: ''
            })
            resolve()
          })
      } else {
        resolve()
      }
    })
  }

  getDataSource = ({ category }) => {
    const { dataSource } = this.props
    let datasourcesingle = {}
    dataSource.map(data => {
      if (
        JSON.stringify(data.submitdata.postSearchCondition.category) == JSON.stringify(category)
      ) {
        datasourcesingle = data
      }
    })
    return datasourcesingle || {}
  }

  getDataSourceperson = ({ category }) => {
    const { peopleDataSource } = this.props
    let datasourcesingle = {}
    peopleDataSource.map(data => {
      if (JSON.stringify(data.submitdata.category) == JSON.stringify(category)) {
        datasourcesingle = data
      }
    })
    return datasourcesingle || {}
  }

  onPullDownRefresh() {
    Taro.vibrateShort()
    this.queryWrap(true)
    let timer = setTimeout(() => {
      clearTimeout(timer)
      stopPullDownRefresh()
    }, 500)
  }

  queryWrap = pulldownRefresh => {
    const { role } = this.props
    this.setState({
      prevRole: this.props.role
    })
    // this.resetOrderData()
    this.onHideScreen()
    if (role == 'personal') {
      this.queryLeft(pulldownRefresh)
    } else {
      this.queryRight(pulldownRefresh)
    }
  }

  queryLeft = pulldownRefresh => {
    this.props.updateState({
      requestOverTop: false
    })

    this.resetDataSource(pulldownRefresh).then(({ dataSource: dataSourceReset }) => {
      // 获取岗位、人才标签列表
      this.props.updateState({
        dataSource: dataSourceReset
      })
      const { barlevecurrent } = this.props
      let submitdata = { ...dataSourceReset[barlevecurrent].submitdata }
      if (pulldownRefresh) {
        submitdata.page = 1
        submitdata.isOld = false
      }
      this.props
        .dorequest({
          dataSourceAll: dataSourceReset,
          barlevecurrent,
          ...submitdata
        })
        .then(() => {
          // 查询岗位数据
          this.props.updateState({
            requestOverTop: true
          })
        })
    })
  }

  queryRight = pulldownRefresh => {
    this.props.updateState({
      requestOverTop: false
    })
    const { barlevecurrent, peopleDataSource } = this.props
    const { barlevelonedata } = this.state
    let type = [barlevelonedata[barlevecurrent].title]
    let submitdata = {}
    // 查询人才数据
    submitdata = {
      type,
      ...peopleDataSource[barlevecurrent].submitdata
    }
    if (pulldownRefresh) {
      submitdata.page = 1
      submitdata.isOld = false
    }
    this.resetPeopleDataSource(pulldownRefresh).then(({ dataSource: dataSourceReset }) => {
      this.props.updateState({
        peopleDataSource: dataSourceReset
      })
      this.props
        .doRequestForPeople({
          dataSourceAll: dataSourceReset,
          barlevecurrent,
          ...submitdata
        })
        .then(() => {
          // 如果数据过少 自动查询老数据
          this.props.updateState({
            requestOverTop: true
          })
          const { peopleDataSource: dataSource } = this.props
          let currentnew = barlevecurrent
          if (dataSource[currentnew].dataSource.length < 3 && currentnew == 2) {
            // 如果数据小于3个， 且数据不是老数据
            if (!submitdata.isOld) {
              submitdata.isOld = true
            }
            this.props.doRequestForPeople({
              dataSourceAll: dataSource,
              dataSource: dataSource[barlevecurrent].dataSource,
              barlevecurrent,
              ...dataSource[barlevecurrent].submitdata
            })
          }
        })
    })
  }
  resetPeopleDataSource = pulldownRefresh => {
    // 重置datasource数据
    return new Promise(resolve => {
      const { barlevelonedata } = this.state
      const { peopleDataSource } = this.props
      let returnDataSource = []
      if (pulldownRefresh) {
        returnDataSource = [...peopleDataSource]
      } else {
        barlevelonedata.map(data => {
          let dataSingle = {
            haveNextPersonPage: true,
            showRightEmpty: false,
            submitdata: {
              page: 1,
              pageSize: 10,
              // 获取老数据的字段
              isOld: false,
              category: [],
              // practiceLabel: 0,
              type: [],
              area: []
            }
          }
          switch (data.title) {
            case '全部':
              break
            case '兼职':
              dataSingle.submitdata.type = ['兼职']
              break
            case '全职':
              dataSingle.submitdata.type = ['全职']
              break
            case '实习':
              dataSingle.submitdata.type = ['实习']
              break
            default:
              break
          }
          dataSingle.dataSource = []
          returnDataSource.push(dataSingle)
        })
      }
      resolve({ dataSource: returnDataSource })
    })
  }

  resetDataSource = pulldownRefresh => {
    // 重置datasource数据
    return new Promise(resolve => {
      const { dataSource } = this.props
      const { barlevelonedata } = this.state
      let returnDataSource = []
      if (pulldownRefresh) {
        returnDataSource = [...dataSource]
      } else {
        barlevelonedata.map(data => {
          let dataSingle = {
            haveNextJobPage: true,
            showLeftEmpty: false,
            submitdata: {
              page: 1,
              pageSize: 10,
              postSearchCondition: {
                anyWhere: 0,
                area: [],
                settlementMethod: [],
                city: ''
              }
            }
          }
          switch (data.title) {
            case '全部':
              break
            case '兼职':
              dataSingle.submitdata.postSearchCondition.type = [0]
              break
            case '全职':
              dataSingle.submitdata.postSearchCondition.type = [1]
              break
            case '实习':
              dataSingle.submitdata.postSearchCondition.practiceLabel = 1
              break
            default:
              break
          }
          dataSingle.dataSource = []
          returnDataSource.push(dataSingle)
        })
      }

      resolve({ dataSource: returnDataSource })
    })
  }

  onSwiperChange = (index, e) => {
    const { role } = this.props
    let { isiPhone } = this.state
    this.props.updateState({
      barlevecurrent: index,
      requestOverTop: false
    })
    if (role == 'personal') {
      this.resetDataSource().then(({ dataSource: dataSourceReset }) => {
        const { barlevecurrent } = this.props
        const submitdata = dataSourceReset[index].submitdata
        this.getScreenData()
        this.props
          .dorequest({ dataSourceAll: dataSourceReset, barlevecurrent, ...submitdata })
          .then(() => {
            // 查询岗位数据
            this.props.updateState({
              requestOverTop: true
            })
          })
      })
    } else {
      this.resetPeopleDataSource().then(({ dataSource: dataSourceReset }) => {
        const { barlevecurrent } = this.props
        const submitdata = dataSourceReset[index].submitdata
        this.getScreenData()
        this.props
          .doRequestForPeople({
            dataSourceAll: dataSourceReset,
            barlevecurrent,
            ...submitdata
          })
          .then(() => {
            this.props.updateState({
              requestOverTop: true
            })
            // 如果数据过少 自动查询老数据
            const { peopleDataSource: dataSource } = this.props
            let currentnew = barlevecurrent
            if (dataSource[currentnew].dataSource.length < 3 && currentnew == 2) {
              // 如果数据小于3个， 且数据不是老数据
              if (!submitdata.isOld) {
                submitdata.isOld = true
              }
              this.props.doRequestForPeople({
                dataSourceAll: dataSource,
                dataSource: dataSource[barlevecurrent].dataSource,
                barlevecurrent,
                ...submitdata
              })
            }
          })
      })
    }
    // 在安卓上设置时间会抖动
    pageScrollTo({
      scrollTop: 260,
      duration: isiPhone ? 300 : 0
    })
    this.onHideScreen()
    this.resetOrderData()
  }

  onClickScreen = index => {
    // 点击打开筛选  如果点击的筛选条件是当前展开的 则隐藏
    const { screenShow, isiPhone, screenIndex } = this.state
    if (screenIndex !== index || !screenShow) {
      this.setState({
        screenShow: true,
        screenIndex: index
      })
    } else {
      this.onHideScreen()
    }
    if (!screenShow) {
      pageScrollTo({
        scrollTop: 260,
        duration: isiPhone ? 300 : 0
      })
    }
  }

  onHideScreen = () => {
    this.setState({
      screenShow: false,
      screenIndex: -1
    })
  }

  onReachBottom = () => {
    // 页面触底回调
    const { role } = this.props
    if (role == 'personal') {
      const { dataSource: dataSourceAll, barlevecurrent } = this.props
      const detail = dataSourceAll[barlevecurrent]
      if (this.requestOver && detail && detail.haveNextJobPage) {
        this.requestOver = false
        const dataSource = detail.dataSource
        const submitdata = deepCopy(detail.submitdata)
        submitdata.page = (submitdata.page || 1) + 1
        this.props
          .dorequest({
            dataSourceAll,
            dataSource,
            barlevecurrent,
            ...submitdata
          })
          .then(data => {
            this.requestOver = true
          })
      }
    } else {
      // 查询人才数据
      const { peopleDataSource: dataSourceAll, barlevecurrent } = this.props
      const detail = dataSourceAll[barlevecurrent]
      if (this.requestOver && detail.haveNextPersonPage) {
        this.requestOver = false
        const dataSource = detail.dataSource
        const submitdata = deepCopy(detail.submitdata)
        submitdata.page = submitdata.page ? submitdata.page + 1 : 2
        this.props
          .doRequestForPeople({
            dataSourceAll,
            dataSource,
            barlevecurrent,
            ...submitdata
          })
          .then(() => {
            this.requestOver = true
            // 如果数据过少 自动查询老数据
            const { peopleDataSource: dataSourceAllNew } = this.props
            let currentnew = barlevecurrent
            if (
              dataSourceAllNew[currentnew].dataSource.length < 3 ||
              dataSourceAllNew[currentnew].dataSource.length ==
                dataSourceAll[currentnew].dataSource.length
            ) {
              // 如果数据小于3个， 且数据不是老数据
              if (!submitdata.isOld) {
                submitdata.isOld = true
              }
              this.props.doRequestForPeople({
                dataSourceAll: dataSourceAllNew,
                dataSource: dataSourceAllNew[currentnew].dataSource,
                barlevecurrent,
                ...submitdata
              })
            }
          })
      }
    }
  }

  formSubmit = e => {
    let { formId } = e.detail
    const { openId, userId } = this.props
    messagePush.insertFormId({ userId, formId, openId })
  }

  onSubmitImg = () => {
    // 点击banner按钮
  }

  getScreenData = () => {
    // 获取筛选数据
    const { landmarkName = '上海', barlevecurrent, companyId } = this.props
    const { screenTitle, barlevelonedata } = this.state
    let screenTitleNew = [...screenTitle]
    let type = this.checkWorkType(barlevecurrent, barlevelonedata)
    Promise.all([
      this.props.queryCate(type), // 获取岗位信息
      getAreaListByCityName(landmarkName), // 获取当前区域信息
      inRecruitPostCategoryRequest({ type }) // 获取公司在招职位
    ]).then(([{ desireList = [] }, { data: datain }, { data: { data: inRecruitData = [] } }]) => {
      const { entry = [] } = datain

      screenTitleNew[0].data = this.setOrderData()
      screenTitleNew[1].data = this.setIndustryCategories(desireList, inRecruitData)
      screenTitleNew[2].data = this.setAreaData(entry || [])
      screenTitleNew[3].data = this.setEducationData()
      this.setState({
        screenTitle: screenTitleNew
      })
    })
  }

  checkWorkType = (barlevecurrent, barlevelonedata) => {
    // 返回筛选信息type 0-兼职 1-全职 2-实习
    let type = 0
    switch (barlevelonedata[barlevecurrent].title) {
      case '兼职':
        type = 0
        break
      case '全职':
        type = 1
        break
      case '实习':
        type = 2
        break
    }
    return type
  }

  onClickScreenItem = ({ index: dataIndex, screenIndex, cardIndex, titleIndex }) => {
    // 点击筛选
    const { role } = this.props
    const { screenTitle } = this.state
    let screenTitleNew = [...screenTitle]
    let screenData = {}
    switch (screenIndex) {
      case 0:
        screenTitleNew[screenIndex].data.map((item, index) => {
          if (dataIndex === index) {
            item.active = true
            screenTitleNew[screenIndex].nickName = item.name
          } else {
            item.active = false
          }
          return item
        })
        this.setState({
          screenTitle: screenTitleNew
        })
        role === 'personal'
          ? (screenData.order = screenTitleNew[screenIndex].data[dataIndex].data)
          : (screenData.sortType = dataIndex)
        this.onHideScreen()
        break
      case 1:
        let dataNew = screenTitleNew[screenIndex].data
        let cateName = []
        dataNew.map((itemData, indexData) => {
          let isThis = indexData === titleIndex
          itemData &&
            itemData.data &&
            itemData.data.map((item, index) => {
              if (cardIndex === index && isThis) {
                item.active = !item.active
                if (item.active) {
                  role === 'personal' && cateName.push(itemData.name)
                  cateName.push(role === 'personal' ? item.name : item.category)
                  screenTitleNew[screenIndex].nickName =
                    role === 'personal' ? item.name : item.category
                } else {
                  delete screenTitleNew[screenIndex]['nickName']
                }
              } else {
                item.active = false
              }
              return item
            })
        })
        if (screenTitleNew[screenIndex].nickName == '全部') {
          delete screenTitleNew[screenIndex]['nickName']
        }
        screenTitleNew[screenIndex].data = dataNew
        this.setState({
          screenTitle: screenTitleNew
        })
        screenData.category = cateName
        this.onHideScreen()
        break
      case 2:
        let dataArea = this.resetAreaList(screenTitle[screenIndex])
        let areaName = ''
        dataArea.map((item, index) => {
          if (cardIndex === index) {
            item.active = true
            areaName = item.name
            screenTitleNew[screenIndex].nickName = item.name
          } else {
            item.active = false
          }
          return item
        })
        if (screenTitleNew[screenIndex].nickName == '全部') {
          delete screenTitleNew[screenIndex]['nickName']
        }
        screenTitle[screenIndex].data = dataArea
        this.setState({
          screenTitle: screenTitleNew
        })
        screenData.area = [areaName]
        this.onHideScreen()
        break
      case 3:
        let dataEdu = this.resetIndustryCategories(screenTitleNew[screenIndex])
        let inEdu = dataEdu[titleIndex].data
        let eduId = ''
        inEdu &&
          inEdu.map((item, index) => {
            if (cardIndex === index) {
              item.active = true
              eduId = item.value
              screenTitleNew[screenIndex].nickName = item.name
            } else {
              item.active = false
            }
            return item
          })
        dataEdu[titleIndex].data = inEdu
        screenTitleNew[screenIndex].data = dataEdu
        if (screenTitleNew[screenIndex].nickName == '全部') {
          delete screenTitleNew[screenIndex]['nickName']
        }
        this.setState({
          screenTitle: screenTitleNew
        })
        screenData.education = eduId
        this.onHideScreen()
        break
    }
    this.screenSearch(screenData)
  }

  resetIndustryCategories = data => {
    return data.data.map(item => {
      item.data.map(itemIn => {
        itemIn.active = false
        return itemIn
      })
      return item
    })
  }

  setIndustryCategories = (data, inRecruitData) => {
    // 初始化职位数据
    const { screenTitle } = this.state
    const { role, companyId, barlevecurrent } = this.props
    let nickName = screenTitle[1].nickName
    let dataNew = []
    let inRecruitDataNew = {
      data: [],
      name: '正在招聘'
    }
    if (role === 'personal') {
      dataNew = data.map(item => {
        item.industryCategories.map(itemIn => {
          itemIn.active = nickName ? itemIn.name === nickName : false
          return itemIn
        })
        item.data = item.industryCategories
        delete item['industryCategories']
        return item
      })
    }
    if (role === 'company' && companyId && inRecruitData.length > 0) {
      inRecruitDataNew.data = inRecruitData.map((item, index) => {
        let itemNew = {}
        itemNew.name = item.name
        itemNew.category = item.category
        itemNew.active = false
        return itemNew
      })
      dataNew.unshift(inRecruitDataNew)
    }
    inRecruitDataNew.data.length &&
      dataNew.unshift({
        name: '',
        data: [
          {
            name: '全部',
            active: nickName ? nickName === '全部' : true
          }
        ]
      })
    return dataNew
  }

  setEducationData = () => {
    // 初始化学历数据
    const { screenTitle } = this.state
    let nickName = screenTitle[3].nickName
    let education = getGlobalData('education')
    let educationNew = [...education]
    educationNew.unshift({ value: 0, name: '全部' })
    educationNew.map((item, index) => {
      item.active = nickName ? item.name === nickName : index === 0
      return item
    })
    return [
      {
        name: '学历',
        data: educationNew
      }
    ]
  }

  setOrderData = () => {
    const { role, latitude, longitude } = this.props
    const { screenTitle } = this.state
    let data =
      role === 'personal'
        ? [
            {
              name: '综合排序',
              active: screenTitle[0].nickName ? screenTitle[0].nickName === '综合排序' : true,
              data: ''
            },
            {
              name: '最近发布',
              active: screenTitle[0].nickName === '最近发布',
              data: 1
            }
          ]
        : [
            {
              name: '推荐人才',
              active: screenTitle[0].nickName ? screenTitle[0].nickName === '推荐人才' : true
            },
            {
              name: '最近发布',
              active: screenTitle[0].nickName === '最近发布'
            }
          ]
    if (role === 'personal' && (latitude || longitude)) {
      data.push({
        name: '离我最近',
        active: screenTitle[0].nickName === '离我最近',
        data: 'distance'
      })
    }
    return data
  }

  resetAreaList = data => {
    return data.data.map(item => {
      item.active = false
      return item
    })
  }

  setAreaData = data => {
    // 初始化区域数据
    const { screenTitle } = this.state
    let dataNew = [...data]
    let nickName = screenTitle[2].nickName
    dataNew.unshift('全部')
    let returnData = dataNew.map((item, index) => {
      if (nickName) {
        if (index == 0) {
          item = {
            name: '全部',
            active: data[index - 1] === nickName
          }
        } else {
          item = {}
          item.name = data[index - 1]
          item.active = data[index - 1] === nickName
        }
      } else {
        if (index == 0) {
          item = {
            name: '全部',
            active: true
          }
        } else {
          item = {}
          item.name = data[index - 1]
          item.active = false
        }
      }
      return item
    })
    return returnData
  }

  screenSearch = screenData => {
    // 筛选后查询岗位 / 人才
    const {
      dataSource: dataSourceAllCompany,
      peopleDataSource: dataSourceAllPersonal,
      barlevecurrent,
      role,
      latitude,
      longitude
    } = this.props
    const dataSourceAll = role == 'personal' ? dataSourceAllCompany : dataSourceAllPersonal
    const detail = dataSourceAll[barlevecurrent]
    if (this.requestOver && role == 'personal') {
      this.requestOver = false
      const dataSource = detail.dataSource
      const submitdata = { ...detail.submitdata }
      submitdata.postSearchCondition = this.dealPostSearch({
        ...submitdata.postSearchCondition,
        ...screenData
      })
      submitdata.page = 1
      submitdata.pageSize = 10
      submitdata.postSearchCondition.latitude = latitude
      submitdata.postSearchCondition.longitude = longitude
      this.props
        .dorequest({
          dataSourceAll,
          dataSource,
          barlevecurrent,
          ...submitdata
        })
        .then(data => {
          let timer = setTimeout(() => {
            clearTimeout(timer)
            const { dataSource } = this.props
            this.props.updateState({
              dataSource
            })
          }, 100)
          this.requestOver = true
        })
    } else {
      // 查询人才数据
      if (this.requestOver) {
        this.requestOver = false
        const submitdata = this.dealPostSearch({
          ...detail.submitdata,
          ...screenData
        })
        submitdata.page = 1
        submitdata.pageSize = 10
        submitdata.isOld = false
        this.props
          .doRequestForPeople({
            dataSourceAll,
            barlevecurrent,
            isOrder: true, // 是否筛选
            ...submitdata
          })
          .then(() => {
            this.requestOver = true
            // 如果数据过少 自动查询老数据
            const { peopleDataSource: dataSource } = this.props
            let currentnew = barlevecurrent
            if (dataSource[currentnew].dataSource.length < 3 && currentnew == 2) {
              // 如果数据小于3个， 且数据不是老数据
              if (!submitdata.isOld) {
                submitdata.isOld = true
              }
              this.props.doRequestForPeople({
                dataSourceAll: dataSource,
                dataSource: dataSource[barlevecurrent].dataSource,
                barlevecurrent,
                ...dataSource[barlevecurrent].submitdata
              })
            }
          })
      } else {
        showToast({
          title: '请稍等'
        })
      }
    }
  }

  resetOrderData = () => {
    // 清空筛选数据 并重置
    const { screenTitle } = this.state
    let screenTitleNew = [...screenTitle]
    screenTitleNew.map(item => {
      delete item['nickName']
      return item
    })
    this.resetIndustryCategories(screenTitleNew[1])
    if (
      screenTitleNew[1].data &&
      screenTitleNew[1].data.length &&
      screenTitleNew[1].data.length &&
      screenTitleNew[1].data[0].data
    ) {
      screenTitleNew[1].data[0].data[0].active = true
    }
    this.resetAreaList(screenTitleNew[2])
    if (screenTitleNew[2].data && screenTitleNew[2].data.length) {
      screenTitleNew[2].data[0].active = true
    }
    this.resetIndustryCategories(screenTitleNew[3])
    if (
      screenTitleNew[3].data &&
      screenTitleNew[3].data.length &&
      screenTitleNew[1].data.length &&
      screenTitleNew[1].data[0].data
    ) {
      screenTitleNew[3].data[0].data[0].active = true
    }
    screenTitleNew[0].data = this.setOrderData()
    this.setState({
      screenTitle: screenTitleNew
    })
  }

  dealPostSearch = data => {
    // 删除掉不需要的筛选条件
    if (!data.order) {
      delete data['order']
    }
    if (!data.sortType) {
      delete data['sortType']
    }
    if (!(data.category && data.category[0]) || data.category[0] === '全部') {
      delete data['category']
    }
    if (data.category && data.category[1] && data.category[1] === '正在招聘') {
      data['category'].pop()
    }
    if (data.area && data.area[0] === '全部') {
      delete data['area']
    }
    if (!data.education) {
      delete data['education']
    }
    return data
  }

  handleTouchMove = e => {
    e.preventDefault()
    e.stopPropagation()
    return
  }

  render() {
    const {
      barlevecurrent,
      role,
      dataSource,
      peopleDataSource,
      homePageBanner,
      requestOverTop,
      landmarkName
    } = this.props
    const { barlevelonedata, screenTitle, screenShow, screenIndex } = this.state
    return (
      <View className="JobView_id89493">
        <TopLocation banner={homePageBanner} />

        <StickyWrap height={100}>
          <View onTouchMove={this.handleTouchMove}>
            <View className={`screen-modal ${screenShow ? 'screen-show' : 'screen-hide'}`}>
              <View
                className={`screen-mask ${screenShow ? 'screen-show' : 'screen-hide'}`}
                onTouchStart={this.onHideScreen}
              />
              <ScrollView
                className={`screen-item ${screenShow ? 'screen-item-show' : 'screen-item-hide'}`}
                scrollY
              >
                {screenTitle.map((item, index) => {
                  return (
                    index === screenIndex && (
                      <ScreenList
                        key={index}
                        barlevecurrent={barlevecurrent}
                        screenIndex={screenIndex}
                        type={item.type}
                        showTitle={item.title}
                        dataSource={item.data}
                        role={role}
                        onTap={this.onClickScreenItem}
                      />
                    )
                  )
                })}
              </ScrollView>
            </View>
            <BarLevelone
              dataSource={barlevelonedata}
              screenTitle={screenTitle}
              screenIndex={screenIndex}
              current={barlevecurrent}
              role={role}
              onChange={this.onSwiperChange}
              onClickScreen={this.onClickScreen}
              style={{ zIndex: 9 }}
            />
          </View>
        </StickyWrap>

        <View className="ad-imgs">
          <Form onSubmit={this.formSubmit} reportSubmit className="ad-imgs-item">
            <Button formType="submit" className="form-btn" onClick={this.onSubmitImg}>
              <Image
                mode="aspectFill"
                src="https://imagesize.hrwork.com/sp/files/4961c2da-ad48-499b-8e6e-820df741076d.png"
              />
            </Button>
          </Form>
          <Form onSubmit={this.formSubmit} reportSubmit className="ad-imgs-item">
            <Button formType="submit" className="form-btn" onClick={this.onSubmitImg}>
              <Image
                mode="aspectFill"
                src="https://imagesize.hrwork.com/sp/files/acf4a1f9-dae8-464b-bae4-0682cdfaa615.png"
              />
            </Button>
          </Form>
        </View>

        {barlevelonedata.map((data, index) => {
          return role == 'personal' ? (
            index == barlevecurrent ? (
              <JobsScrollWrap
                onShowDialog={this.onShowDialog}
                onPullDownRefresh={this.onPullDownRefresh}
                dataSource={dataSource[barlevecurrent]}
                barlevecurrent={barlevecurrent}
                submitdata={dataSource.submitdata}
                requestOverTop={requestOverTop}
                landmarkName={landmarkName}
              />
            ) : null
          ) : index == barlevecurrent ? (
            <ResumeScrollWrap
              dataSource={peopleDataSource[barlevecurrent]}
              barlevecurrent={barlevecurrent}
              submitdata={peopleDataSource.submitdata}
              requestOverTop={requestOverTop}
            />
          ) : null
        })}
      </View>
    )
  }
}

export default JobView
